//
//  GHNetWorkTool.swift
//  Browser
//
//  Created by 刘光华 on 16/4/27.
//  Copyright © 2016年 liuguanghua. All rights reserved.
//

import UIKit
import AFNetworking

// MARK:- 请求类型
enum RequestType {
    
    case POST
    case GET
    
}


class GHNetWorkTool: AFHTTPSessionManager {

    // 注意这里要声明变量类型,不然类型推导不出来
    /// 单例对象
    static let shareInstance: GHNetWorkTool = {
        
        let instance = GHNetWorkTool()
        
        instance.responseSerializer.acceptableContentTypes?.insert("text/html")
        return instance
        
    }()
}


// MARK:- 基本请求
extension GHNetWorkTool {
    
    func requset(requset: RequestType, URLString: String, parameters: [String: AnyObject], completion: (result: AnyObject?, error: NSError?)-> ()) {
        
        // 请求成功的回调
        let successCallBack = { (task: NSURLSessionDataTask, result: AnyObject?) -> Void in
            completion(result: result, error: nil)
        }
        
        // 请求失败的回调
        let failureCallBack = { (task: NSURLSessionDataTask?, error: NSError) -> Void in
            completion(result: nil, error: error)
        }
        
        // 发送POST请求或者GET请求
        switch requset {
            case .POST:
                POST(URLString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
            case .GET:
                GET(URLString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        }
        
    }
    
}


// MARK:- 首页数据请求
extension GHNetWorkTool {
    
    func loadHomeData(offset: Int, finish: (result: [[String: NSObject]]?, error: NSError?)-> ()) {
        
        let URLString = "http://mobapi.meilishuo.com/2.0/twitter/popular.json"
        
        let parameters = ["offset" : "\(offset)", "limit" : "30", "access_token" : "b92e0c6fd3ca919d3e7547d446d9a8c2"]
        
        requset(.GET, URLString: URLString, parameters: parameters) { (result, error) -> () in
            
            // 过滤空值
            guard error == nil else {
                
                finish(result: nil, error: error)
                return
            }
            
            guard let result = result as? [String: AnyObject] else {
                
                finish(result: nil, error: NSError(domain: "data error", code: -1000, userInfo: nil))
                return
                
            }
            
            // 回调结果
            finish(result: result["data"] as? [[String: NSObject]], error: nil)
            
            
            
        }
        
        
    }
    
    
    
}



